﻿using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class MemberInitNode : ExpRepresentationBase
    {
        [DataMember]
        public NewInstanceNode NewExpression { get; set; }

        [DataMember]
        public MemberBindingNodeBase[] Bindings { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            NewExpression newExpression = (NewExpression)NewExpression.ToExpression(exepressionBuilderCache);
            MemberBinding[] memberBindings = new MemberBinding[Bindings.Length];
            for (int index = 0; index < memberBindings.Length; index++)
            {
                memberBindings[index] = Bindings[index].ToMemberBinding(exepressionBuilderCache);
            }
            return Expression.MemberInit(newExpression, memberBindings);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            NewExpression = (NewInstanceNode)NewExpression.Traverse(action);

            foreach (var binding in Bindings)
            {
                binding.TraverseChildren(action);
            }
        }

        public override string ToString()
        {
            string description = string.Format("{0} {{{1}}}", NewExpression, string.Join(", ", (object[])Bindings));
            return description;
        }
    }
}